package com.mc.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.mc.api.constant.Constants;
import com.mc.api.domain.*;
import com.mc.api.domain.page.CltResultPage;
import com.mc.api.domain.page.PageRequest;
import com.mc.api.service.*;
import com.mc.api.utils.HttpUtil;
import com.mc.api.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/clt")
public class CltController {
    private static final Logger log = LoggerFactory.getLogger(CltController.class);
    @Autowired
    private ICltTaskService cltTaskService;

    @Autowired
    private ICltPositionService cltPositionService;

    @Autowired
    private ICltResultService cltResultService;

    @Autowired
    private ILabAuthenticateService labAuthenticateService;

    @Autowired
    private ICltMultimediaService cltMultimediaService;


    /**
     * 查询采集任务
     */
    @GetMapping("/task/{userId}")
    @ResponseBody
    public Object taskByuserId(@PathVariable("userId") String userId) {
        List<CltTask> list = new ArrayList<CltTask>();
        CltTask cltTask = cltTaskService.selectCltTask(userId);
        CltTask cltTaskDefault = cltTaskService.selectCltTaskByID(Constants.DEFAULT_TASK_ID);
        if(cltTask != null ){
            cltTask.setIsDefault("0");
            cltTaskDefault.setIsDefault("1");
            list.add(cltTask);
        }else{
            cltTaskDefault.setIsDefault("0");
        }
        list.add(cltTaskDefault);
        Object obj = JSONArray.toJSON(list);
        return obj;
    }

    @GetMapping("/plant/{date}")
    @ResponseBody
    public Object plant(@PathVariable("date") String date){
        CustomError error = new CustomError();
        try {
            Date lastSynDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            JSONObject object = new JSONObject();
            object.put("data",cltTaskService.selectPlantByDate(date));
            object.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //Object obj = JSONArray.toJSON(cltTask.selectPlantByDate(date));
            return object;

        } catch (ParseException e) {
            e.printStackTrace();
            error.setCode("500");
            error.setMsg("时间格式异常");
        }
        return JSONArray.toJSON(error);


    }
    @PostMapping("/data/dictionary")
    @ResponseBody
    public Object dictionary(@RequestBody JSONObject jsonObject){
        CustomError error = new CustomError();
        String date = jsonObject.getString("date");
        try {
            Date lastSynDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            String type = jsonObject.getString("type");

        } catch (ParseException e) {
            e.printStackTrace();
            error.setCode("500");
            error.setMsg("时间格式异常");
        }
        return JSONArray.toJSON(error);
    }

    @PostMapping("/uploadMulterFile")
    @ResponseBody
    public Object uploadMulterFile (@RequestParam MultipartFile file) {

        String name =file.getOriginalFilename(); //获取图片的名称
        log.info(name);
        String uuid  = UUID.randomUUID().toString().replaceAll("-","");
        FileOutputStream picOutput = null;//设置存储路径
        try {
            picOutput = new FileOutputStream("/home/industry/pictures/"+uuid+"-"+name);
            picOutput.write(file.getBytes());//获取字节流直接写入到磁盘内

        } catch (FileNotFoundException e) {
            log.info("qqq");
            e.printStackTrace();
        }catch (IOException e){
            log.info("aaa");
            e.printStackTrace();
        } finally{
            try {
                picOutput.close();//关闭字节流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("path", "/home/industry/pictures/"+uuid+"-"+name);
        result.put("fileName", uuid+"-"+name);
        return result;
    }


    @PostMapping("/position")
    @ResponseBody
    public Object position (HttpServletRequest request){
        try{
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            List<CltPosition>  cltPositionList = new ArrayList<CltPosition>();
            cltPositionList = JSONObject.parseArray(sb.toString(),CltPosition.class);
            for(CltPosition cltPosition : cltPositionList){
                String uuid  = UUID.randomUUID().toString().replaceAll("-","");
                if(cltPositionService.selectCltPositionByRecordTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cltPosition.getRecordTime())) > 0){

                }else{
                    cltPosition.setId(uuid);
                    cltPositionService.insertCltPosition(cltPosition);
                }
                if(cltPositionService.selectCltPositionByUserId(cltPosition.getUserId())==0){
                    cltPosition.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    cltPositionService.insertCltPositionNow(cltPosition);
                }else{
                    cltPositionService.updateCltPositionNow(cltPosition);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            JSONObject result = new JSONObject();
            result.put("code", "500");
            result.put("msg", "参数异常");
            return result;
        }

        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("msg", "ok");
        return result;
    }

    /**
     * 上传采
     * @param request
     * @return
     */

    @PostMapping("/add")
    @ResponseBody
    public Object add(@RequestBody JSONArray jsonArry,HttpServletRequest request){
        User user = TokenUtil.getLoginUser(request);
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("f","pjson");
        params.add("frollbackOnFailure", "true");
        // 获取输入流
        log.info("请求参数："+jsonArry.toString());
        //jsonParam.getJSONArray()
       for(int i = 0;i < jsonArry.size();i++){
           JSONObject jsonParam=jsonArry.getJSONObject(i);
           log.info("请求参数："+jsonParam.toString());
           String type = jsonParam.getString("cltType");
           if(type.equals(Constants.GERMPLASM)){
               CltResultGermplasm germplasm = jsonParam.getObject("data",CltResultGermplasm.class);
               germplasm.setCreateUserId(user.getUserName());
               if(cltTaskService.selectCltTaskByID(germplasm.getTaskId()) ==null){
                   JSONObject result = new JSONObject();
                   result.put("code", "500");
                   result.put("msg", "采集任务不存在");
                   return result;
               }
               String uuid1  = UUID.randomUUID().toString().replaceAll("-","");
               String uuid2  = UUID.randomUUID().toString().replaceAll("-","");
               //if(germplasm.getN)
               germplasm.setResultId(uuid1);
               germplasm.setCltResultId(uuid1);
               germplasm.setId(uuid2);
               germplasm.setCltType(Constants.GERMPLASM);
               cltResultService.insertCltResultGermplasm(germplasm);
               String cltTime = null;
//               if(germplasm.getCollectionTime() !=null && !"".equals(germplasm.getCollectionTime())){
//                   cltTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(germplasm.getCollectionTime());
//               }
//               params.add("features", "[{\"attributes\": {\n" +
//                       "    \"NAME\": \"\",\n" +
//                       "    \"TOPOGRAPHY\": \""+germplasm.getTopography()+"\",\n" +
//                       "    \"SLOPE_DEGREE\": \""+germplasm.getSlopeDegree()+"\",\n" +
//                       "    \"SLOPE_ASPECT\": \""+germplasm.getSlopeAcpect()+"\",\n" +
//                       "    \"SLOPE_POSITION\": \""+germplasm.getSlopePosition()+"\",\n" +
//                       "    \"ASSOCIATE_SPECIES\": \""+germplasm.getAssociateSpecies()+"\",\n" +
//                       "    \"CLT_TIME\": \""+cltTime+"\",\n" +
//                       "    \"TOPOGRAPHY\": \""+germplasm.getTopography()+"\",\n" +
//                       "    \"LOCATION\": \""+germplasm.getLocation()+"\",\n" +
//                       "    \"COUNTY\": \""+germplasm.getAreaCode()+"\",\n" +
//                       "   },\n" +
//                       "   \"geometry\": {\n" +
//                       "    \"x\": "+germplasm.getLongitude()+",\n" +
//                       "    \"y\": "+germplasm.getLatitude()+"\n" +
//                       "   }}]");
//
//               try{
//                   germplasm.setObjectId(RestTemplate(params,"addFeatures"));
//                   cltResultService.updateCltResult(germplasm);
//               }catch (Exception e){
//
//               }finally {
//
//               }

           }else if(type.equals(Constants.SPECIMEN)){
               CltResultSpecimen specimen = jsonParam.getObject("data",CltResultSpecimen.class);
               specimen.setCreateUserId(user.getUserName());
               CltTask cl = cltTaskService.selectCltTaskByID(specimen.getTaskId());
               if(cltTaskService.selectCltTaskByID(specimen.getTaskId())==null ){
                   JSONObject result = new JSONObject();
                   result.put("code", "500");
                   result.put("msg", "采集任务不存在");
                   return result;
               }
               String uuid1  = UUID.randomUUID().toString().replaceAll("-","");
               String uuid2  = UUID.randomUUID().toString().replaceAll("-","");
               specimen.setResultId(uuid1);
               specimen.setCltResultId(uuid1);
               specimen.setId(uuid2);
               specimen.setCltType(Constants.SPECIMEN);
               cltResultService.insertCltResultSpecimen(specimen);
//               String cltTime = null;
//               if(specimen.getCollectionTime() !=null && !"".equals(specimen.getCollectionTime())){
//                   cltTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(specimen.getCollectionTime());
//               }
//               params.add("features", "[{\"attributes\": {\n" +
//                       "    \"NAME\": \"\",\n" +
//                       "    \"TOPOGRAPHY\": \""+specimen.getTopography()+"\",\n" +
//                       "    \"SLOPE_DEGREE\": \""+specimen.getSlopeDegree()+"\",\n" +
//                       "    \"SLOPE_ASPECT\": \""+specimen.getSlopeAcpect()+"\",\n" +
//                       "    \"SLOPE_POSITION\": \""+specimen.getSlopePosition()+"\",\n" +
//                       "    \"ASSOCIATE_SPECIES\": \""+specimen.getAssociateSpecies()+"\",\n" +
//                       "    \"CLT_TIME\": \""+cltTime+"\",\n" +
//                       "    \"TOPOGRAPHY\": \""+specimen.getTopography()+"\",\n" +
//                       "    \"LOCATION\": \""+specimen.getLocation()+"\",\n" +
//                       "    \"COUNTY\": \""+specimen.getAreaCode()+"\"\n" +
//                       "   },\n" +
//                       "   \"geometry\": {\n" +
//                       "    \"x\": "+specimen.getLongitude()+",\n" +
//                       "    \"y\": "+specimen.getLatitude()+"\n" +
//                       "   }}]");
//
//               try{
//                   specimen.setObjectId(RestTemplate(params,"addFeatures"));
//                   cltResultService.updateCltResult(specimen);
//               }catch (Exception e){
//
//               }finally {
//
//               }


           }else{
               JSONObject result = new JSONObject();
               result.put("code", "500");
               result.put("msg", "采集类型不存在");
               return result;
           }

       }
        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("msg", "ok");
        return result;
    }

//    @PostMapping("/add/specimen1")
//    @ResponseBody
//    public Object addSpecimen(@RequestBody CltResultSpecimen specimen){
//        String uuid1  = UUID.randomUUID().toString().replaceAll("-","");
//        String uuid2  = UUID.randomUUID().toString().replaceAll("-","");
//        specimen.setResultId(uuid1);
//        specimen.setCltResultId(uuid1);
//        specimen.setId(uuid2);
//        specimen.setType("specimen");
//        cltResultService.insertCltResultSpecimen(specimen);
//        JSONObject result = new JSONObject();
//        result.put("code", "200");
//        result.put("msg", "ok");
//        return result;
//    }
    @PostMapping("/get")
    @ResponseBody
    public Object get (@RequestBody CltResultPage CltResultPage){

        log.info(CltResultPage.getPageNum()+"-----"+CltResultPage.getPageNum());
        return JSONArray.toJSON(cltResultService.selectCltResultPage(CltResultPage));
        //cltResultService.selectCltResultPage();
    }
    @PostMapping("/get/info")
    @ResponseBody
    public Object get (@RequestBody JSONObject jsonObject){
        String id = jsonObject.getString("id");
        CltResult cltResult = cltResultService.selectCltResultById(id);
        if(cltResult != null){
            if(cltResult.getCltType().equals(Constants.GERMPLASM)){
                return JSONArray.toJSON(cltResultService.selectCltResultGermplasm(id));
            } else if (cltResult.getCltType().equals(Constants.SPECIMEN)){
                return JSONArray.toJSON(cltResultService.selectCltResultSpecimen(id));
            }
            JSONObject result = new JSONObject();
            result.put("code", "500");
            result.put("msg", "数据有误");
            return result;
        }else{
            JSONObject result = new JSONObject();
            result.put("code", "500");
            result.put("msg", "采集不存在");
            return result;
        }

        //cltResultService.selectCltResultPage();
    }

    /**
     * 新增鉴定信息
     * @param labAuthenticate
     * @param request
     * @return
     */
    @PostMapping("/authenticate")
    @ResponseBody
    public  Object authenticate(@RequestBody LabAuthenticate labAuthenticate,HttpServletRequest request){
        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("msg", "ok");
        if(labAuthenticate.getName().isEmpty()||labAuthenticate.getFamilyName().isEmpty()||labAuthenticate.getCategoryName().isEmpty()){
            result.put("code", "500");
            result.put("msg", "名称不能为空");
            return result;
        }
        if(labAuthenticate.getResultId().isEmpty()){
            result.put("code", "500");
            result.put("msg", "采集编号不能为空");
            return result;
        }
        CltResult cltResult = cltResultService.selectCltResultById(labAuthenticate.getResultId());
        if(cltResult==null){
            result.put("code", "500");
            result.put("msg", "采集编号不存在");
            return result;
        }

        User user = TokenUtil.getLoginUser(request);
        String uuid  = UUID.randomUUID().toString().replaceAll("-","");
        labAuthenticate.setCltId(labAuthenticate.getResultId());
        labAuthenticate.setAuthenticateId(uuid);
        labAuthenticate.setCreateUserId(user.getUserName());
        labAuthenticateService.insertLabAuthenticate(labAuthenticate);
        if(cltResult.getObjectId() !=null && !"".equals(cltResult.getObjectId())){
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            params.add("features", "[{\"attributes\": {\n" +
                    "    \"OBJECTID\":"+cltResult.getObjectId()+"\n" +
                    ",\"NAME\": \""+labAuthenticate.getName()+"\",\n" +
                    "\"FAMILY\":\""+labAuthenticate.getFamilyName()+"\",\n" +
                    "\"GENUS\":\""+labAuthenticate.getCategoryName()+"\",\n" +
                    "\"SPECIES\":\""+labAuthenticate.getScientificName()+"\"\n" +
                    "   }\n" +
                    "}]");


            try{
                RestTemplate(params,"updateFeatures");
            }catch (Exception e){

            }finally {

            }
        }

        return result;
    }
    @GetMapping("/get/authenticate/{id}")
    @ResponseBody
    public  Object getAuthenticate(@PathVariable String id){
        return JSONArray.toJSON(labAuthenticateService.selectLabAuthenticateById(id));
    }

    @GetMapping("/get/task/{username}")
    @ResponseBody
    public Object task(@PathVariable String username){
        return JSONArray.toJSON(cltTaskService.selectTaskByUserName(username));
    }

    @PostMapping("/get/cltResult/byUserID/{userID}")
    @ResponseBody
    public Object cltResultByUserID(@PathVariable String userID,@RequestBody PageRequest resultPage){
        int pageNum = resultPage.getPageNum();
        int pageSize = resultPage.getPageSize();
        if(pageNum==0&&pageSize==0){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content",cltResultService.selectCltResultByTaskID(userID));
            //jsonObject.put("content",cltResultService.selectCltResultByTaskID(userID))
            return jsonObject;
        }else{
            return JSONArray.toJSON(cltResultService.selectCltResultByTaskID(userID,resultPage));
        }

    }
    @GetMapping("/get/cltResult/byID/{id}")
    @ResponseBody
    public Object cltResultByID(@PathVariable String id){
        CltResult cltResult = cltResultService.selectCltResultById(id);
        CltMultimedia cltMultimedia = new CltMultimedia();
        cltMultimedia.setCltId(id);
        List<CltMultimedia> listClt = cltMultimediaService.selectCltMultimediaList(cltMultimedia);
        LabAuthenticate labAuthenticate = new LabAuthenticate();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

        if(cltResult.getCltType().equals(Constants.GERMPLASM)){
            CltResultGermplasm germplasm = cltResultService.selectCltResultGermplasm(id);
            labAuthenticate.setCltId(id);
            germplasm.setPhoto(listClt);
            germplasm.setCollectionDate(format.format(germplasm.getCollectionTime()));
            germplasm.setAuthenticateName(labAuthenticateService.selectLabAuthenticateList(labAuthenticate));
            //germplasm.se
            return JSONArray.toJSON(germplasm);
            //germplasm.setUserId();

        }else if(cltResult.getCltType().equals(Constants.SPECIMEN)){
            CltResultSpecimen specimen = cltResultService.selectCltResultSpecimen(id);
            labAuthenticate.setCltId(id);
            labAuthenticateService.selectLabAuthenticateList(labAuthenticate);
            specimen.setPhoto(listClt);
            specimen.setCollectionDate(format.format(specimen.getCollectionTime()));
            specimen.setAuthenticateName(labAuthenticateService.selectLabAuthenticateList(labAuthenticate));
            return JSONArray.toJSON(specimen);
        }
        JSONObject result = new JSONObject();
        result.put("code", "500");
        result.put("msg", "ID不存在");
        return result;
    }
    @GetMapping("/get/statistical/by/{userId}")
    @ResponseBody
    public Object statisticalByUserId(@PathVariable String userId){

        Clt cltResult = new Clt();
        cltResult.setCltType(Constants.GERMPLASM);//种子
        int gerAll = cltResultService.countCltResult(cltResult);
        cltResult.setCltType(Constants.SPECIMEN);//标本
        int speAll = cltResultService.countCltResult(cltResult);
        cltResult.setCollectionDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        cltResult.setCltType(Constants.GERMPLASM);//种子
        int gerToday = cltResultService.countCltResult(cltResult);
        cltResult.setCltType(Constants.SPECIMEN);//标本
        int speToday = cltResultService.countCltResult(cltResult);
        cltResult.setUserId(userId);
        cltResult.setCollectionDate(null);
        cltResult.setCltType(Constants.GERMPLASM);//种子
        int gerMy = cltResultService.countCltResult(cltResult);
        cltResult.setCltType(Constants.SPECIMEN);//标本
        int speMy = cltResultService.countCltResult(cltResult);
        JSONObject result = new JSONObject();
        result.put("gerAll", gerAll);
        result.put("gerToday", gerToday);
        result.put("gerMy", gerMy);
        result.put("speAll", speAll);
        result.put("speToday", speToday);
        result.put("speMy", speMy);
        result.put("soilAll", 0);
        result.put("soilToday", 0);
        result.put("soilMy", 0);
        result.put("wetAll", 0);
        result.put("wetToday", 0);
        result.put("wetMy", 0);
        return result;
    }
    public String RestTemplate(MultiValueMap<String, String> params,String action){
        RestTemplate restTemplate = new RestTemplate();
        log.info("================ start =====================");
        log.info("params:"+params.toString());
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);
        ResponseEntity<String> response = restTemplate.postForEntity(
                Constants.GIS_SERVER_URL+action,
                requestEntity,
                String .class);
        String jsonObject = response.getBody();
        if(action.equals("addFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("addResults").getJSONObject(0).getString("objectId");
        }else if(action.equals("updateFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("updateResults").getJSONObject(0).getString("objectId");
        }else{
            return null;
        }

    }
}
